package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//路径匹配器，匹配的时候还支持通配符，用来判断请求的路径是不是白名单中的请求，是否放行
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //1.获取本次请求的uri
        String requestURI = request.getRequestURI();

        log.info("拦截到请求：{}",requestURI);
        //1.1定义不需要处理的请求路径，也就是白名单
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**", //这样即使是没登陆直接访问了index.html，该页面也是没有数据的
                "/front/**",
                "/common/**",
                "/user/sendMsg",//移动端发送短信
                "/user/login" //移动端登录
        };
        //2.判断本次请求是否需要处理
        boolean check = check(requestURI, urls);//自定义的一个匹配请求路径的方法

        //3.如果不需要处理。则直接放行
        if (check){
            log.info("本次请求不需要处理：{}",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //4-1.后台员工---判断登录状态，如果已经登录直接放行，看session中是否有该用户的id--employee
       if (request.getSession().getAttribute("employee")!=null){
           
           log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
           //将登录成功的员工id保存到threadLocal中
           Long empId = (Long) request.getSession().getAttribute("employee");
           BaseContext.setCurrentId(empId);
           filterChain.doFilter(request,response);
           return;
       }

        //4-2.移动端用户---判断登录状态，如果已经登录直接放行
        if (request.getSession().getAttribute("user")!=null){

            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            //将登录成功的员工id保存到threadLocal中
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

       log.info("用户未登录");
       //5.如果未登录，就返回到登录页面
        //通过输出流的方向想前端页面响应json数据，前端的request.js中
        // 会根据R对象中的数据判断进行登录页面的跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 进行路径匹配的方法，检查本次请求是否需要放行
     * @param requestURI
     * @param urls
     * @return
     */
    public boolean check(String requestURI,String[] urls){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
